﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;

namespace RaceList.Admin.Relay
{
    public partial class AwardUsers : System.Web.UI.Page
    {
        ipowdb_suibian_webDataContext db = ConnHelper.ipowdb_suibian_web();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataBind();
                FenYe();
            }
        }

        #region 下拉框
        private void DataBind()
        {
            var awardUsers = GetDataSource(firstLoad: true);
            var awardGroup = awardUsers.GroupBy(s => s.awardId);
            var result = new List<Activity_Awards>();
            foreach (var item in awardGroup)
            {
                result.Add(item.First().Activity_Awards);
            }
            ddlAwardName.DataTextField = "name";
            ddlAwardName.DataValueField = "Id";
            ddlAwardName.DataSource = result;
            ddlAwardName.DataBind();
            ddlAwardName.Items.Insert(0, new ListItem("所有奖品", "all"));

            ddlIsCheck.Items.Insert(0, new ListItem("所有", "all"));
            ddlIsCheck.Items.Insert(1, new ListItem("未兑奖", false.ToString()));
            ddlIsCheck.Items.Insert(2, new ListItem("已兑奖", true.ToString()));
        }

        protected void ddlAwardName_SelectedIndexChanged(object sender, EventArgs e)
        {
            FenYe();
        }

        protected void ddlIsCheck_SelectedIndexChanged(object sender, EventArgs e)
        {
            FenYe();
        }
        #endregion
        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int? ID = Convert.ToInt32(e.CommandArgument.ToString());
            Activity_AwardUser awardUser = db.Activity_AwardUser.SingleOrDefault(s => s.Id == ID);

            if (awardUser != null)
            {
                string action = string.Empty;
                try
                {
                    switch (e.CommandName)
                    {
                        case "CheckAward":
                            if (!awardUser.isCheck)
                            {
                                awardUser.isCheck = true;
                                awardUser.CheckDate = DateTime.Now;
                                db.SubmitChanges();
                            }
                            action = "修改";
                            break;
                    }

                    this.Message.Text = "操作成功";
                }
                catch (Exception ex)
                {
                    StringHelper.Alert(this, "操作失败！", string.Empty);
                    this.Message.Text = "操作失败，失败原因：" + ex.Message + "！详细原因请查看错误日志。";
                }
                FenYe();
            }
            else
            {
                StringHelper.Alert(this, "此用户不存在，请您刷新本页面后继续操作！", string.Empty);
            }
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#EFF3FB'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='White'");
            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            FenYe();
        }

        #region 分页
        protected int GetCrrentPage()
        {
            int currentPage = 1;
            if (Request.Form["__EVENTARGUMENT"] != null)
            {
                Int32.TryParse(Request.Form["__EVENTARGUMENT"], out currentPage);
                currentPage = currentPage == 0 ? 1 : currentPage;
            }
            return currentPage;
        }
        private List<Activity_AwardUser> GetDataSource(bool firstLoad = false)
        {
            var list = db.Activity_AwardUser.Where(s => s.isAward).OrderByDescending(s => s.addTime).ToList();
            if (!firstLoad)
            {
                if (ddlAwardName.SelectedValue != "all")
                {
                    list = list.Where(s => s.awardId.ToString() == ddlAwardName.SelectedValue).ToList();
                }
                if (ddlIsCheck.SelectedValue != "all")
                {
                    list = list.Where(s => s.isCheck.ToString() == ddlIsCheck.SelectedValue).ToList();
                }

                #region 时间控制
                try
                {
                    var date = Convert.ToDateTime((string) txtAwardStartDate.Text.Trim());
                    list = list.Where(s => s.addTime >= date).ToList();
                }
                catch
                {

                }
                try
                {
                    var date = Convert.ToDateTime((string) txtAwardEndDate.Text.Trim());
                    list = list.Where(s => s.addTime <= date).ToList();
                }
                catch
                {

                }
                try
                {
                    var date = Convert.ToDateTime((string) txtCheckStartDate.Text.Trim());
                    list = list.Where(s => s.CheckDate >= date).ToList();
                }
                catch
                {

                }
                try
                {
                    var date = Convert.ToDateTime((string) txtCheckEndDate.Text.Trim());
                    list = list.Where(s => s.CheckDate <= date).ToList();
                }
                catch
                {

                }
                #endregion
            }
            //只显示用户提交了自己个人信息的记录
            return list;
        }
        protected object GetCurrentPageDataSource()
        {
            var list = GetDataSource();

            var skipNum = (Paging1.CurrentPage - 1) * Paging1.PageSize;
            list = list.Skip(skipNum).Take(Paging1.PageSize).ToList();

            return list.Select(s => new
            {
                Id = s.Id,
                SumScore = s.Activity_Relay.SumScore,
                NickName = s.Activity_Relay.WeixinUser.Nickname,
                Name = s.name,
                Phone = s.phone,
                AddTime = s.addTime,
                SponsorName = GetSponsor(s.Activity_Relay.SponsorId),
                AwardName = s.Activity_Awards.name,
                IsAward = s.isAward,
                IsCheck = s.isCheck,
                CheckDate = s.CheckDate,
            });
        }

        public string GetSponsor(int? sponsorId)
        {
            if (sponsorId.HasValue)
            {
                var sponsor = db.Activity_Sponsor.Where(s => s.Id == sponsorId).FirstOrDefault();
                if (sponsor != null)
                    return sponsor.Name;
            }
            return "";
        }

        protected int GetTotalNum()
        {
            return GetDataSource().Count;
        }
        protected void FenYe()
        {
            Paging1.PageSize = 10;
            Paging1.CurrentPage = GetCrrentPage();
            Paging1.TotalNum = GetTotalNum();
            Paging1.Paging_Bind();
            gvList.DataSource = GetCurrentPageDataSource();
            gvList.DataBind();
        }
        protected void btnPage_Click(object sender, EventArgs e)
        {
            FenYe();
        }
        #endregion

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            FenYe();
        }

        public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
        {
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            OutPutExcel();
        }

        public void OutPutExcel()
        {
            //定义文档类型、字符编码  
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312";
            //下面这行很重要， attachment 参数表示作为附件下载，您可以改成 online在线打开  
            //filename=FileFlow.xls 指定输出文件的名称，注意其扩展名和指定文件类型相符，可以为：.doc 　　 .xls 　　 .txt 　　.htm  
            Response.AppendHeader("Content-Disposition", "attachment;filename=FileFlow.xls");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            //Response.ContentType指定文件类型 可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html 或其他浏览器可直接支持文档  
            Response.ContentType = "application/ms-excel";
            this.EnableViewState = false;
            //　定义一个输入流  
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            var source = GetDataSource();
            var obj = source.Select(s => new
            {
                Id = s.Id,
                SumScore = s.Activity_Relay.SumScore,
                NickName = s.Activity_Relay.WeixinUser.Nickname.SubHtml(10),
                Name = s.name.SubHtml(10),
                Phone = s.phone,
                AddTime = s.addTime,
                SponsorName = GetSponsor(s.Activity_Relay.SponsorId),
                AwardName = s.Activity_Awards.name,
                IsAward = s.isAward,
                IsCheck = s.isCheck,
                CheckDate = s.CheckDate,
            });
            this.gvList.DataSource = obj;
            gvList.DataBind();
            gvList.RenderControl(oHtmlTextWriter);
            //this 表示输出本页，你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件  
            Response.Write(oStringWriter.ToString());
            FenYe();
            Response.End();
        }
    }

    public static class StringEx
    {
        public static string SubHtml(this string str, int length)
        {
            var len = str.Length;
            if (len > length)
                return str.Substring(0, length);
            return str.Substring(0, len);
        }
    }
}